﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using STLGROUP.Layers.Presentations.FormBase;
using STLGROUP.Layers.Common;
using STLGROUP.Layers.DataAccessLayers;
using QuanLyBanHang.Class;
using System.Collections;
using STLGROUP.Layers.BLL;

namespace QuanLyBanHang
{
    /// <summary>
    /// MF006A - Quan Ly Hoa Don Ban Si
    /// </summary>
    /// <author>Van Long</author>
    /// <date>22/04/2012</date>
    public partial class MF006A : frmManager
    {
        /// <summary>
        /// ytu
        /// </summary>
        #region Member variables

        private DT_HoaDonBLL _hoaDon;
        private SortedList<string, clsChiTietHoaDonTmp> _lstCTHD = new SortedList<string, clsChiTietHoaDonTmp>();
        private ArrayList _lst = new ArrayList();
        private int _index;
        private DT_SanPham _currentProduct;
        private decimal _TongTien;
        private decimal _GiamGia;
        private decimal _ThanhTien;
        private decimal _tienKhachTra = 0;
        private KM_GiamGiaHoaDon _giamGiaHD = null;

        private int _idLoaiHoaDon;

        #endregion

        #region Constructors

        public MF006A()
        {
            InitializeComponent();

            _hoaDon = new DT_HoaDonBLL();
        }

        #endregion

        #region Protected Methods

        #region LoadData
        protected override void LoadData()
        {
            cboMaKhachHang.DataSource = Cache.Context.DT_KhachHang.Where(s => (!s.IsHuy.HasValue || s.IsHuy == !Const.DA_HUY_KHACH_HANG));
            cboMaKhachHang.ValueMember = "IDKhachHang";
            cboMaKhachHang.DisplayMember = "MaKhachHang";

            _index = 0;
            _lst.Clear();
            cboMaKhachHang.SelectedIndex = -1;
            txtTenKhachHang.Text = "";
        } 
        #endregion

        #region AddNew
        protected override void AddNew()
        {
            _index = 0;
            this.rdoBanLe.Checked = true;
            this.tsbCancel.Enabled = true;
            this.tsbThem.Enabled = false;
            this.tsbLuu.Enabled = true;
            this.pnlChiTiet.Enabled = true;
            this.tblThongTinHoaDon.Enabled = true;
            this.tblThanhToan.Enabled = false;
            this.tblControl.Enabled = true;

            ThongTinTaoHoaDon();
            _lstCTHD.Clear();
            ShowOrderDetails(); 
        } 
        #endregion

        #region CancelAddinng

        protected override void CancelAddinng()
        {
            this.pnlChiTiet.Enabled = false;
            this.tsbCancel.Enabled = false;
            this.tsbLuu.Enabled = false;
            this.tsbThem.Enabled = true;
            this.tblControl.Enabled = false;

            if (_lstCTHD.Values.Count > 0)
            {
                foreach (var item in _lstCTHD.Values)
                {
                    GiamSoLuongSanPham(item.MaSanPham, item.SoLuong, false);
                }
                _lstCTHD.Clear();
                ShowOrderDetails();
                TinhTien();
                txtTienKhachTra.Text = string.Empty;
            }
        } 

        #endregion
        
        protected override int UpdateData()
        {
            if (rdoBanLe.Checked)
            {
                _idLoaiHoaDon = (int)StructsEnums.EnumLoaiHoaDon.HoaDonBanLe;
            }
            if (rdoBanSi.Checked)
            {
                _idLoaiHoaDon = (int)StructsEnums.EnumLoaiHoaDon.HoaDonBanSi;
            }

            if (_lstCTHD.Values.Count == 0)
            {
                UICommon.ShowMessegeInfo(Const.MSG_CHUA_CHON_SAN_PHAM);
                return -1;
            }

            if ((!decimal.TryParse(txtTienKhachTra.Text, out _tienKhachTra) || _tienKhachTra < _ThanhTien * (decimal)Const.SO_TIEN_TOI_THIEU_THANH_TOAN_TRUOC) && rdoBanSi.Checked)
            {
                MessageBox.Show("Số tiền khách hàng phải trải là " + _ThanhTien.ToString(Const.DINH_DANG_HIEN_THI_TIEN) +
                                            ". Số tiền thanh toán trước tối thiểu là " + (_ThanhTien * (decimal)Const.SO_TIEN_TOI_THIEU_THANH_TOAN_TRUOC).ToString(Const.DINH_DANG_HIEN_THI_TIEN));
                txtTienKhachTra.Focus();
                return -1;
            }

            if ((!decimal.TryParse(txtTienKhachTra.Text, out _tienKhachTra) || _tienKhachTra < _ThanhTien) && rdoBanLe.Checked)
            {
                MessageBox.Show("Khách hàng phải trả " + _ThanhTien .ToString(Const.DINH_DANG_HIEN_THI_TIEN)+
                                        ". Số tiền nhập vào còn thiếu " + (_ThanhTien - _tienKhachTra).ToString(Const.DINH_DANG_HIEN_THI_TIEN));
                txtTienKhachTra.Focus();
                return -1;
            }  

            IDbTransaction transaction = null;

            try
            {
                Cache.Context.Connection.Open();
                transaction = Cache.Context.Connection.BeginTransaction();

                Cache.Context.SaveChanges();

                int idHoaDon = AddHoaDon();

                if (idHoaDon != -1)
                {
                    AddChiTietHoaDon(_lstCTHD, idHoaDon);

                    transaction.Commit();
                    Cache.Context.Connection.Close();
                    tsbThem.Enabled = true;

                    txtConNo.Text = (_tienKhachTra >= _ThanhTien) ? "0" : (_ThanhTien - _tienKhachTra).ToString(Const.DINH_DANG_HIEN_THI_TIEN);
                    txtTienTraLaiKhach.Text = (_tienKhachTra < _ThanhTien) ? "0" : (_tienKhachTra - _ThanhTien).ToString(Const.DINH_DANG_HIEN_THI_TIEN);

                    base.UpdateData();

                    //print order
                    if (_idLoaiHoaDon == (int)StructsEnums.EnumLoaiHoaDon.HoaDonBanLe)
                    {                        
                        RF007 frm = new RF007() { IDHoaDon = idHoaDon };
                        frm.ShowDialog();
                    }
                    if (_idLoaiHoaDon == (int)StructsEnums.EnumLoaiHoaDon.HoaDonBanSi)
                    {
                        RF008 frm = new RF008() { IDHoaDon = idHoaDon };
                        frm.ShowDialog();
                    }

                    Cache.Context.Connection.Close();
                    return 1;

                }
                else
                {
                    if (transaction != null)
                    {
                        transaction.Rollback();
                    }
                    Cache.Context.Connection.Close();
                    return -1;
                }
            }
            catch (Exception ex)
            {
                if (transaction != null)
                {
                    transaction.Rollback();                     
                }
                Cache.Context.Connection.Close();
                UICommon.ShowMessgeString(ex.ToString(), "Lỗi"); 
                return -1;
            }
        }
        
        #region AddDataBinding

        protected override void AddDataBinding()
        {
            cboMaSanPham.DataSource = Cache.Context.DT_SanPham.Where(s => (!s.IDTrangThaiSanPham.HasValue || s.IDTrangThaiSanPham == Const.DA_HUY_SAN_PHAM));
            cboMaSanPham.ValueMember = "IDSanPham";
            cboMaSanPham.DisplayMember = "MaSanPham";

            cboMaSanPham.SelectedIndex = -1;
        }  

        #endregion

        #endregion

        #region Private Methods

        #region AddChiTietHoaDon
        private void AddChiTietHoaDon()
        {
            if (iipSL.MaxValue == 0)
            {
                UICommon.ShowMessegeInfo(Const.MSG_SAN_PHAM_DANG_CHON_DA_HET_HANG);
                return;
            }

            try
            {
                clsChiTietHoaDonTmp cthd = new clsChiTietHoaDonTmp();
                cthd.IDSanhPam = _currentProduct.IDSanPham;
                cthd.MaSanPham = _currentProduct.MaSanPham;
                cthd.TenSanPham = _currentProduct.TenSanPham;
                cthd.SoLuong = iipSL.Value;
                cthd.DonViTinh = _hoaDon.GetDonViTinh(_currentProduct.IDDonViTinh);
                cthd.GiaBan = (rdoBanSi.Checked) ? decimal.Parse(txtGiaSi.Text) : decimal.Parse(txtGiaLe.Text);
                cthd.TongTien = cthd.GiaBan * cthd.SoLuong;
                cthd.GiamGia = _hoaDon.GetGiamGiaSanPham(_currentProduct.IDSanPham);
                cthd.ThanhTien = cthd.TongTien - cthd.GiamGia;

                if (_lstCTHD.Keys.Contains(cthd.MaSanPham))
                {
                    _lstCTHD[cthd.MaSanPham].SoLuong += cthd.SoLuong;
                    _lstCTHD[cthd.MaSanPham].GiamGia += cthd.GiamGia;
                    _lstCTHD[cthd.MaSanPham].TongTien += cthd.TongTien;
                    _lstCTHD[cthd.MaSanPham].ThanhTien += cthd.ThanhTien;
                }
                else
                {
                    _index++;
                    cthd.STT = _index;
                    _lstCTHD.Add(cthd.MaSanPham, cthd);
                }

                _currentProduct.SoLuongTonKho -= cthd.SoLuong;
                txtSLToiDa.Text = _currentProduct.SoLuongTonKho.ToString();
                iipSL.Value = iipSL.MinValue;

                ShowOrderDetails();
            }
            catch { }
        } 
        #endregion

        #region GiamSoLuongSanPham
        private void GiamSoLuongSanPham(string maSanPham, int soLuongGiam, bool huySanPham)
        {
            try
            {
                if (_lstCTHD[maSanPham].SoLuong == soLuongGiam && huySanPham)
                {
                    _lstCTHD.Remove(maSanPham);

                    if (_lstCTHD.Values.Count == 0)
                    {
                        CancelAddinng();
                    }
                }
                else
                {
                    _lstCTHD[maSanPham].SoLuong -= soLuongGiam;
                }
                _currentProduct = _hoaDon.GetSanPham(maSanPham);

                _currentProduct.SoLuongTonKho += soLuongGiam;

                if (_currentProduct.IDSanPham == (int)cboMaSanPham.SelectedValue)
                {
                    ShowThongTinSanPhamDangChon();
                }

                ShowOrderDetails();
                TinhTien();
            }
            catch
            {
            }

        } 
        #endregion

        #region TinhTien

        private void TinhTien()
        {
            _TongTien = _GiamGia = _ThanhTien = 0;
            decimal soTienGiam = 0;
            _giamGiaHD = null;

            foreach (var item in _lstCTHD.Values)
            {
                _TongTien += item.TongTien;
                _GiamGia += item.GiamGia;
                _ThanhTien += item.ThanhTien;
            }

            //GiamGia
            _giamGiaHD = GetGiamGiaHoaDon(_TongTien);

            if (_giamGiaHD != null&&_giamGiaHD.HeSoGiamGia.HasValue)
            {
                soTienGiam = (_TongTien * (decimal)_giamGiaHD.HeSoGiamGia) / 100;
            }

            //Thanh tien.
            _ThanhTien = _TongTien - soTienGiam;

            //fill to textbox.
            txtTongTien.Text = _TongTien.ToString(Const.DINH_DANG_HIEN_THI_TIEN);            
            txtGiamGia.Text = soTienGiam.ToString(Const.DINH_DANG_HIEN_THI_TIEN);
            txtThanhTien.Text = _ThanhTien.ToString(Const.DINH_DANG_HIEN_THI_TIEN);

            if (rdoBanLe.Checked)
            {
                txtTienKhachTra.Text = _ThanhTien.ToString(Const.DINH_DANG_HIEN_THI_TIEN);
            }
        } 

        #endregion

        private KM_GiamGiaHoaDon GetGiamGiaHoaDon(decimal pTongTien)
        {
            //Giam gia hoa don.
            KM_GiamGiaHoaDon giamGiaHD = (from km in Cache.Context.KM_ChuongTrinhKhuyenMai
                          join gg in Cache.Context.KM_GiamGiaHoaDon on km.IDChuongTrinhKM equals gg.IDChuongTrinhKM
                          where km.NgayBatDau <= DateTime.Today
                          && km.NgayKetThuc >= DateTime.Today
                          && gg.GiaTriToiThieu <= pTongTien
                          select gg).FirstOrDefault();
            
            return giamGiaHD;

        }


        #region SanPhamInfo
        private void SanPhamInfo(DT_SanPham sp)
        {
            txtTenSanPham.Text = _currentProduct.TenSanPham;
            txtSLToiDa.Text = _currentProduct.SoLuongTonKho.ToString();
            txtGiaSi.Text = _currentProduct.GiaBanSi.ToString();
            txtGiaLe.Text = _currentProduct.GiaBanLe.ToString();
        } 
        #endregion

        #region ShowOrderDetails
        private void ShowOrderDetails()
        {
            if (_lstCTHD.Values.Count > 0)
            {
                clsChiTietHoaDonTmp2 cthd;
                _lst.Clear();
                int stt = 1;

                foreach (var item in _lstCTHD.Values)
                {
                    cthd = new clsChiTietHoaDonTmp2(item);
                    cthd.STT = stt;
                    _lst.Add(cthd);
                    stt++;
                }
                dgvSanPham.DataSource = null;
                dgvSanPham.DataSource = _lst;
            }
            else
            {
                dgvSanPham.DataSource = null;
            }
        } 
        #endregion

        #region ThongTinTaoHoaDon

        private void ThongTinTaoHoaDon()
        {
            _TongTien = _GiamGia = _ThanhTien = _tienKhachTra = 0;
            txtTongTien.Text = txtGiamGia.Text = txtThanhTien.Text = txtConNo.Text = txtTienTraLaiKhach.Text = "0";
            txtTienKhachTra.Text = string.Empty;

            _lstCTHD.Clear();
            ShowOrderDetails();

            cboMaKhachHang.SelectedIndex = -1;
            cboMaSanPham.SelectedIndex = -1;
            txtTenKhachHang.Text = "";
        }

        #endregion

        #region ShowThongTinSanPhamDangChon
        private void ShowThongTinSanPhamDangChon()
        {
            try
            {
                int idSanPham = int.Parse(cboMaSanPham.SelectedValue.ToString());
                _currentProduct = _hoaDon.GetSanPham(idSanPham);
                SanPhamInfo(_currentProduct);
            }
            catch {}
            
        } 
        #endregion

        #region ShowTenKhachHang
        private void ShowTenKhachHang()
        {
            try
            {
                txtTenKhachHang.Text = _hoaDon.GetTenKhachHangByIDKhachHang((int)cboMaKhachHang.SelectedValue);
            }
            catch { }
        } 
        #endregion

        #region ChonKhachHang
        private void ChonKhachHang()
        {
            int idKhachHang;
            MF001._isShowButtonChon = true;
            var frm = new MF001();
            frm.ShowDialog();

            idKhachHang = MF001.GetIDKhachHang();

            if (idKhachHang != 0)
            {
                cboMaKhachHang.SelectedValue = idKhachHang;
            }
        } 
        #endregion

        #region ChonSanPham
        private void ChonSanPham()
        {
            int idSanPham;
            MF004._isShowButtonChon = true;
            var frm = new MF004();
            frm.ShowDialog();

            idSanPham = MF004.GetIDSanPham();

            if (idSanPham != 0)
            {
                cboMaSanPham.SelectedValue = idSanPham;
            }
        } 
        #endregion

        #region GiamSoLuongSanPham
        private void GiamSoLuongSanPham()
        {
            string maSanPham = dgvSanPham.CurrentRow.Cells["colMaSanPham"].Value.ToString();
            int soLuong = int.Parse(dgvSanPham.CurrentRow.Cells["colSL"].Value.ToString());

            _currentProduct = _hoaDon.GetSanPham(maSanPham);

            MF006E frm = new MF006E(_currentProduct, soLuong);
            frm.ShowDialog();

            int soLuongGiam = MF006E.GetSoLuongGiam();

            if (soLuongGiam != 0)
            {
                GiamSoLuongSanPham(maSanPham, soLuongGiam, true);
            }
        } 
        #endregion

        #region AddHoaDon

        private int AddHoaDon()
        {
            try
            {
                DT_HoaDon hd = new DT_HoaDon();
                hd.IDLoaiHoaDon = _idLoaiHoaDon;//sang edit
                hd.TongTien = _TongTien;
                hd.DaTra = (_ThanhTien > _tienKhachTra) ? _tienKhachTra : _ThanhTien;
                hd.IDDoiTac = (int?)cboMaKhachHang.SelectedValue;
                hd.IDGiamGiaHoaDon = _giamGiaHD != null ? (int?)_giamGiaHD.IDGiamGiaHoaDon : null;//sang edit
                hd.NgayTao = UICommon.GetDateTime();
                hd.NguoiTao = UICommon.CurrentUserInfo.IDNhanVien;
                hd.IDNhanVien = UICommon.CurrentUserInfo.IDNhanVien;

                if (hd.DaTra == hd.TongTien)
                {
                    hd.IDTrangThaiHoaDon = (int?)StructsEnums.EnumTrangThaiHoaDon.DaThanhToan;
                }
                else
                {
                    hd.IDTrangThaiHoaDon = (int?)StructsEnums.EnumTrangThaiHoaDon.ConNo;
                }

                Cache.Context.DT_HoaDon.AddObject(hd);
                Cache.Context.SaveChanges();

                var IDHoaDon = Cache.Context.DT_HoaDon.Max(s => s.IDHoaDon);
                int idHoaDon = int.Parse(IDHoaDon.ToString());

                var hoaDonNew = Cache.Context.DT_HoaDon.Where(s => s.IDHoaDon == idHoaDon).FirstOrDefault();
                hoaDonNew.MaHoaDon = _hoaDon.GetMaHoaDon(idHoaDon);

                return idHoaDon;
            }
            catch (Exception ex)
            {
                UICommon.ShowMessgeString(ex.ToString(), "Lỗi");
            }
            return -1;
        } 

        #endregion

        #region AddChiTietHoaDon
                
        private void AddChiTietHoaDon(SortedList<string, clsChiTietHoaDonTmp> lstCTHD, int idHoaDon)
        {
            try
            {
                if (lstCTHD.Values.Count > 0)
                {
                    foreach (var item in lstCTHD.Values)
                    {
                        DT_ChiTietHoaDon cthd = new DT_ChiTietHoaDon();
                        cthd.IDHoaDon = idHoaDon;
                        cthd.IDSanPhan = item.IDSanhPam;
                        cthd.SoLuong = item.SoLuong;
                        cthd.GiaSanPham = item.GiaBan;
                        cthd.GiamGia = item.GiamGia;
                        cthd.NguoiTao = UICommon.CurrentUserInfo.IDNhanVien;
                        cthd.NgayTao = UICommon.GetDateTime();

                        Cache.Context.DT_ChiTietHoaDon.AddObject(cthd);
                        Cache.Context.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                UICommon.ShowMessgeString(ex.ToString(), "Lỗi");
            }

        } 

        #endregion

        #endregion

        #region Events

        private void cboMaSanPham_SelectionChangeCommitted(object sender, EventArgs e)
        {
            ShowThongTinSanPhamDangChon();
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            if (cboMaKhachHang.SelectedValue == null && rdoBanSi.Checked)
            {
                UICommon.ShowMessegeInfo(Const.MSG_KHACH_HANG_KHONG_DUOC_BO_TRONG);
                return;
            }
            if (cboMaSanPham.SelectedValue == null)
            {
                UICommon.ShowMessegeInfo(Const.MSG_CHUA_CHON_SAN_PHAM);
                return;
            }
            if (iipSL.Value == 0)
            {
                UICommon.ShowMessegeInfo(Const.MSG_VUI_LONG_CHON_SO_LUONG_SAN_PHAM);
                return;
            }
            if (int.Parse(txtSLToiDa.Text) == 0)
            {
                UICommon.ShowMessegeInfo(Const.MSG_SAN_PHAM_DANG_CHON_DA_HET_HANG);
                return;
            }
            if (int.Parse(txtSLToiDa.Text) < iipSL.Value)
            {
                UICommon.ShowMessegeInfo(Const.MSG_SO_LUONG_SAN_PHAM_CHON_PHAI_NHO_HON_HOAC_BANG_SO_LUONG_TOI_DA);
                return;
            }

            tblThongTinHoaDon.Enabled = false;
            tblThanhToan.Enabled = true;
            txtTienKhachTra.Focus();
            AddChiTietHoaDon();
            TinhTien();
        }

        private void btnSanPham_Click(object sender, EventArgs e)
        {
            ChonSanPham();
        }

        private void btnKhachHang_Click(object sender, EventArgs e)
        {
            ChonKhachHang();
        }

        private void cboMaKhachHang_SelectedValueChanged(object sender, EventArgs e)
        {
            ShowTenKhachHang();
        }

        private void dgvSanPham_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == Const.INDEX_COLUMN_CHON_GIAM_SO_LUONG_SAN_PHAM)
            {
                GiamSoLuongSanPham();
            }
        }

        private void cboMaSanPham_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboMaSanPham.SelectedValue == null)
            {
                txtTenSanPham.Text = "";
                txtSLToiDa.Text = "0";
            }
            else
            {
                ShowThongTinSanPhamDangChon();
            }
        }

        private void txt_TextChanged(object sender, EventArgs e)
        {
            double thanhTien = 0;
            if (double.TryParse(txtThanhTien.Text, out thanhTien))
            {
                lblTienBangChu.Text = UICommon.NumberToString(thanhTien);
            }
            else
            {
                lblTienBangChu.Text = string.Empty;
            }
        }

        private void txtTienKhachTra_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (decimal.TryParse(txtTienKhachTra.Text, out _tienKhachTra))
                {
                    txtConNo.Text = (_tienKhachTra >= _ThanhTien) ? "0" : (_ThanhTien - _tienKhachTra).ToString(Const.DINH_DANG_HIEN_THI_TIEN);
                    txtTienTraLaiKhach.Text = (_tienKhachTra < _ThanhTien) ? "0" : (_tienKhachTra - _ThanhTien).ToString(Const.DINH_DANG_HIEN_THI_TIEN);
                }
                else
                {
                    UICommon.ShowMessegeInfo(Const.MSG_SO_TIEN_NHAP_KHONG_HOP_LE);
                }
            }

        }

        #endregion
    }
}
